package de.tv.weatherox;

import org.apache.commons.beanutils.BeanUtils;

import javax.persistence.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.*;
import java.util.logging.*;

public class UpdateForecastsServlet extends HttpServlet {

    public static final Logger LOGGER = Logger.getLogger(UpdateForecastsServlet.class.getName());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        LOGGER.info("Starting forecast update");
        WeatherForecastBuilder builder = WeatherForecastBuilder.create(new LiveWetterochsPage());
        EntityManager em = null;
        try {
            em = EMF.get().createEntityManager();
            for (Forecast forecast : builder.getDailyForecasts()) {
                Query query = em.createQuery("SELECT f FROM Forecast f WHERE f.id = :id");
                query.setParameter("id", forecast.getId());
                @SuppressWarnings("unchecked")
                List<Forecast> existingForecasts = query.getResultList();
                em.getTransaction().begin();
                Date created = new Date();
                if (existingForecasts.size() == 0) {
                    LOGGER.info("Creating " + forecast.getId());
                } else {
                    LOGGER.info("Updating " + forecast.getId());
                    Forecast originalForecast = existingForecasts.get(0);
                    created = originalForecast.getCreated();
                }
                forecast.setCreated(created);
                em.persist(forecast);
                em.getTransaction().commit();
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
}
